import { reactive } from 'vue'

const TOKEN_KEY = 'COINPAY-TOKEN'
const USER_INFO_KEY = 'COINPAY-USERINFO'

export const state = reactive<{
    token: string | null | undefined
    userInfo: Api.Auth.UserInfo | null | undefined
}>({
    token: localStorage.getItem(TOKEN_KEY),
    userInfo: localStorage.getItem(USER_INFO_KEY)
        ? (JSON.parse(localStorage.getItem(USER_INFO_KEY) as string) as Api.Auth.UserInfo)
        : null
})

export const actions = {
    setToken: (v: string) => {
        state.token = v
        localStorage.setItem(TOKEN_KEY, v)
        console.log('set token', v)
    },

    setUserInfo: (v: Api.Auth.UserInfo) => {
        state.userInfo = v
        localStorage.setItem(USER_INFO_KEY, JSON.stringify(v))
    },

    clear() {
        state.token = ''
        state.userInfo = null

        localStorage.removeItem(TOKEN_KEY)
        localStorage.removeItem(USER_INFO_KEY)
    }
}
